<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Adminlog Controller
 * Build by Phuc Nguyen
 * Contact : nguyenvanphuc0626@gmail.com
 */

class Statistic_model extends MY_Model{
	
	public function __construct(){
		parent::__construct();
		$this->table_name = 'book_sales_statistic';
	}
        
        public function selectAllById($params){
                $sql = "SELECT * FROM {$this->table_name} WHERE owner = '{$params['onwer']}' AND lastupdated = '{$params['lastupdated']}'";
//                die($sql);
                $query  = $this->db->query($sql); 
                return $query->result();
        }
        
        public function updateAction($params){
                $sql = 'UPDATE '.$this->table_name.' SET `'.$params['term'].'` = `'.$params['term'].'` + 1 WHERE `owner` = "'.$params['owner'].'" AND lastupdated = "'.$params['lastupdated'].'"';
                $this->db->query($sql);
                return $this->db->affected_rows();
        }
        
        public function updateCalltime($params){
                $sql = 'UPDATE '.$this->table_name.' SET `'.$params['term'].'` = `'.$params['term'].'` + '.$params['phone_calltime'].' WHERE `owner` = "'.$params['owner'].'" AND lastupdated = "'.$params['lastupdated'].'"';
                $this->db->query($sql);
                return $this->db->affected_rows();
        }
        
        public function statiticUsers($beginTime=NULL,$endTime=NULL){
            $this->db->select('usr.id,usr.group_id,usr.username,usr.firstname,usr.lastname, sum(st.phone_busy) AS phone_busy,sum(st.phone_limited) AS phone_limited,sum(st.callback) AS callback,sum(st.callok) AS callok,sum(st.phone_calltime) AS phone_calltime, st.lastupdated AS lastupdated');
            $this->db->from($this->table_name .' AS st');
            $this->db->join('users AS usr','usr.id = st.owner','inner');
            $this->db->where('usr.active',1);
            $this->db->where('(usr.group_id = 74 OR usr.group_id = 78)');//sale & booker
            if($beginTime){
                $this->db->where('`st`.`lastupdated` >=',$beginTime);
            }
            if($endTime){
                $this->db->where('`st`.`lastupdated` <=',$endTime);
            }
            if($beginTime == NULL AND $endTime = NULL){
                $this->db->where('DATE(`st`.`lastupdated`) = CURDATE()');
            }
            $this->db->group_by('`st`.`owner`');
            $query = $this->db->get();
            return $query->result();
        }
        
        public function init_data(){
		redirect('auth/statiticsHr/lists');
	}
}